package com.example.active.sf;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/17 8:39
 */
public class ProducerConsumer2
{
    static ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://192.168.0.118:61616");

    public static void main(String[] args)
    {
        try
        {
            System.out.println("消费者2");
            Connection connection = factory.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建目的地
            Topic topic = session.createTopic("topic01");
            //创建消费者
            MessageConsumer consumer = session.createConsumer(topic);
//            for(;;){
//                //生产者产生的消息就是TextMessage
//                TextMessage receive = (TextMessage) consumer.receive();
//                if(null != receive){
//                    System.out.println("接收消息："+receive.getText());
//                }else {
//                    break;
//                }
//            }

            //设置监听器
            consumer.setMessageListener(message -> {
                if(message instanceof TextMessage &&null !=message){
                    try
                    {
                        TextMessage textMessage = ((TextMessage) message);
                        System.out.println("接收消息："+textMessage.getText());
                    } catch (JMSException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
            System.in.read();//保证控制台不灭
            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException | IOException e)
        {
            e.printStackTrace();
        }
    }
}
